//
//  HistoryViewController.m
//  Anyair
//
//  Created by karlcool on 14-5-15.
//  Copyright (c) 2014年 Karlcool. All rights reserved.
//

#import "HistoryViewController.h"

@interface HistoryViewController ()

@end

@implementation HistoryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithType:(int)type {
    
    if ([super init]) {
        dataType = type;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = AIR_GRAY;
    
    if ([LRUserManager createManager].userPhone.length==0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登陆后才能查看历史记录" message:nil delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alert show];
    }
    
    historyArray = [[[LRDatabaseManager createDatabase]getHistoryArrayByPhone:[LRUserManager createManager].userPhone AndType:dataType] mutableCopy];
    
    historyTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, [UIScreen mainScreen].bounds.size.height-110) style:UITableViewStylePlain];
    historyTable.dataSource = self;
    historyTable.delegate = self;
    historyTable.backgroundColor = AIR_GRAY;
    historyTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    historyTable.rowHeight = 100;
    [self.view addSubview:historyTable];

    
    refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.view.bounds.size.height,self.view.frame.size.width, self.view.bounds.size.height)];
    refreshHeaderView.delegate = self;
    refreshHeaderView.title1 = @"释放开始更新";
    refreshHeaderView.title2 = @"下拉更新";
    refreshHeaderView.title3 = @"更新中";
    [historyTable addSubview:refreshHeaderView];
    [refreshHeaderView refreshLastUpdatedDate];
    NSString *historyType;
    //第一次自动加载历史记录
    BOOL loadHistory;
    if (dataType==0) {
        historyType = @"pm25";
        loadHistory = [[NSUserDefaults standardUserDefaults]boolForKey:@"loadPMHistory"];
    } else if (dataType==1) {
        historyType = @"co2";
        loadHistory = [[NSUserDefaults standardUserDefaults]boolForKey:@"loadCO2History"];
    } else if (dataType==2) {
        historyType = @"hcho";
        loadHistory = [[NSUserDefaults standardUserDefaults]boolForKey:@"loadHCHOHistory"];
    }

    if (!loadHistory) {
        dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_LOW ,0),^{
            NSDictionary *resposeDic = [[LRHttpManager createHttpManager]queryHistoryByPhone:[LRUserManager createManager].userPhone AndTime:nil AndType:historyType AndPage:@"0"];

            NSArray *tempArray = [resposeDic objectForKey:@"contents"];
            for (NSDictionary *tempDic in tempArray) {
                HistoryModel *tempModel = [[HistoryModel alloc]init];
                
                tempModel.historyDate = [tempDic objectForKey:@"sendtime"];
                if ([[tempDic objectForKey:@"placediy"] isEqualToString:@"无自定义地址"]) {
                    tempModel.historyAddress = [tempDic objectForKey:@"address"];
                } else {
                    tempModel.historyAddress = [tempDic objectForKey:@"placediy"];
                }
                tempModel.historyID = [tempDic objectForKey:@"\"geotable_id\""];
                if (dataType==0) {
                    tempModel.historyValue = [tempDic objectForKey:@"pm"];
                } else if (dataType==1) {
                    
                } else if (dataType==2) {
                    tempModel.historyValue = [tempDic objectForKey:@"hcho"];
                }
                
                LRDatabaseManager *manager=[LRDatabaseManager createDatabase];
                [manager.dataQueue inDatabase:^(FMDatabase *db){
                    [db open];
                    
                    BOOL result = [db executeUpdate:@"insert into HistoryTable(UserPhone,HistoryDate,HistoryValue,HistoryAddress,HistoryType) values(?,?,?,?,?)",[LRUserManager createManager].userPhone,tempModel.historyDate,tempModel.historyValue,tempModel.historyAddress,[NSNumber numberWithInt:dataType]];
                    NSLog(@"历史记录插入数据库%@",result?@"成功":@"失败");
                    [db close];
                }];
                
                NSLog(@"!!!%@",tempDic);
            }
            dispatch_async (dispatch_get_main_queue(),^{
                if ([[resposeDic objectForKey:@"code"] integerValue]==0) {
                    NSLog(@"获取历史记录成功");
                    [[NSUserDefaults standardUserDefaults]setObject:[LRTools getNowTime] forKey:@"lastHistory"];
                    historyArray = [[[LRDatabaseManager createDatabase]getHistoryArrayByPhone:[LRUserManager createManager].userPhone AndType:dataType] mutableCopy];
                    [historyTable reloadData];
                    if (dataType==0) {
                        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"loadPMHistory"];
                    } else if (dataType==1) {
                        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"loadCO2History"];
                    } else if (dataType==2) {
                        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"loadHCHOHistory"];
                    }
                } else {
                    NSLog(@"获取历史记录失败");
                    MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                    [self.view addSubview:shortHub];
                    [shortHub setLabelText:@"获取历史记录失败,请稍后再试"];
                    [shortHub setMode:MBProgressHUDModeText];
                    [shortHub hide:YES afterDelay:1];
                    [shortHub show:YES];
                }
                
            });
        });
        if (dataType==0) {
            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"lastPMHistory"];
        } else if (dataType==2) {
            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"lastHOCOHistory"];
        }
        
        
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return historyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    HistoryCell *cell = (HistoryCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"HistoryCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = AIR_GRAY;
        cell.backView.backgroundColor = [UIColor whiteColor];
        cell.backView.layer.cornerRadius = 5;
        cell.backView.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3].CGColor;
        cell.backView.layer.borderWidth = 0.5;
        cell.addressView.userInteractionEnabled = NO;
        if (dataType==0) {
            cell.unitLabel.text = @"ug/m³";
        } else if (dataType==2) {
            cell.unitLabel.text = @"ppm";
        } else if (dataType==1) {
            cell.unitLabel.text = @"ppm";
        }
        
    }
    HistoryModel *tempModel = historyArray[indexPath.row];
    cell.dateLabel.text = [LRTools turnTimeByTime:tempModel.historyDate];
    cell.valueLabel.text = [NSString stringWithFormat:@"%i",(int)tempModel.historyValue.floatValue];
    cell.valueLabel.textColor = [LRTools setColorForValue:tempModel.historyValue AndType:dataType];
    cell.addressView.text = tempModel.historyAddress;
    
    return cell;
}

#pragma mark - UIScrollViewDelegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    
}

#pragma mark - EGORefreshTableDelegate
- (void)egoRefreshTableDidTriggerRefresh:(EGORefreshPos)aRefreshPos {
    
    [refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:historyTable];
    
    NSString *historyType;
    if (dataType==0) {
        historyType = @"pm25";
    } else if (dataType==1) {
        historyType = @"co2";
    } else if (dataType==2) {
        historyType = @"hcho";
    }
    dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_LOW ,0),^{
        
        NSString *lastTime;
        if (dataType==0) {
            lastTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"lastPMHistory"];
        } else if (dataType==2) {
            lastTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"lastHOCOHistory"];
        }
        NSDictionary *resposeDic = [[LRHttpManager createHttpManager]queryHistoryByPhone:[LRUserManager createManager].userPhone AndTime:lastTime AndType:historyType AndPage:@"0"];
        
        NSArray *tempArray = [resposeDic objectForKey:@"contents"];
        
        for (NSDictionary *tempDic in tempArray) {
            HistoryModel *tempModel = [[HistoryModel alloc]init];
            
            tempModel.historyDate = [tempDic objectForKey:@"sendtime"];
            if ([[tempDic objectForKey:@"placediy"] isEqualToString:@"无自定义地址"]||((NSString*)[tempDic objectForKey:@"placediy"]).length<=1) {
                tempModel.historyAddress = [tempDic objectForKey:@"address"];
            } else {
                tempModel.historyAddress = [tempDic objectForKey:@"placediy"];
            }
            tempModel.historyID = [tempDic objectForKey:@"\"geotable_id\""];
            if (dataType==0) {
                tempModel.historyValue = [tempDic objectForKey:@"pm"];
            } else if (dataType==1) {
                
            } else if (dataType==2) {
                tempModel.historyValue = [tempDic objectForKey:@"hcho"];
            }
            
            LRDatabaseManager *manager=[LRDatabaseManager createDatabase];
            [manager.dataQueue inDatabase:^(FMDatabase *db){
                [db open];
                
                BOOL result = [db executeUpdate:@"insert into HistoryTable(UserPhone,HistoryDate,HistoryValue,HistoryAddress,HistoryType) values(?,?,?,?,?)",[LRUserManager createManager].userPhone,tempModel.historyDate,tempModel.historyValue,tempModel.historyAddress,[NSNumber numberWithInt:dataType]];
                NSLog(@"历史记录插入数据库%@",result?@"成功":@"失败");
                [db close];
            }];
            
            NSLog(@"!!!%@",tempDic);
        }
 
        dispatch_async (dispatch_get_main_queue(),^{
            if ([[resposeDic objectForKey:@"code"] integerValue]==0) {
                NSLog(@"获取历史记录成功");
                needReload = YES;
                [self finishReloadingData];
                if (dataType==0) {
                    [[NSUserDefaults standardUserDefaults]setObject:[LRTools getNowTime] forKey:@"lastPMHistory"];
                } else if (dataType==2) {
                    [[NSUserDefaults standardUserDefaults]setObject:[LRTools getNowTime] forKey:@"lastHOCOHistory"];
                }
                
                
            } else {
                NSLog(@"获取历史记录失败");
                MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                [self.view addSubview:shortHub];
                [shortHub setLabelText:@"获取历史记录失败,请稍后再试"];
                [shortHub setMode:MBProgressHUDModeText];
                [shortHub hide:YES afterDelay:1];
                [shortHub show:YES];
                needReload = NO;
                [self finishReloadingData];
                
            }
        });
    });
    
}
- (BOOL)egoRefreshTableDataSourceIsLoading:(UIView*)view {

    return NO;
}

- (void)finishReloadingData{
	
	if (refreshHeaderView) {
        [refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:historyTable];
    }
    [historyArray removeAllObjects];
    historyArray = [[[LRDatabaseManager createDatabase]getHistoryArrayByPhone:[LRUserManager createManager].userPhone AndType:dataType] mutableCopy];
    
    if (needReload) {
        [self performSelector:@selector(reloadTableView) withObject:nil afterDelay:0.5];
    }
    
}

- (void)reloadTableView {
    [historyTable reloadData];
}

@end
